package me.zhengjie.app.modules.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.zhengjie.app.modules.security.security.JwtUser;
import me.zhengjie.app.modules.user.service.UserInfoService;
import me.zhengjie.entity.user.UserInfo;
import me.zhengjie.enums.CommonEnums;
import me.zhengjie.exception.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public UserDetails loadUserByUsername(String username){
        UserInfo queryUser = new UserInfo();
        queryUser.setLoginName(username);
        UserInfo user = userInfoService.getOne(Wrappers.query(queryUser));
        if (user == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return createJwtUser(user);
        }
    }

    public UserDetails createJwtUser(UserInfo user) {
        return new JwtUser(
                user.getId(),
                user.getLoginName(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
                user.getPhone(),
                null,
                CommonEnums.BooleanEnum.TURE.getValue().equals(user.getValid()),
                user.getCreateTime(),
                user.getLastPasswordResetDate()
        );
    }
}
